package com.others.util;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.link.inout.AuthenticationOutput;
import com.link.po.Account;
import com.link.service.AuthenticationService;
  
 
public class CookieUtils implements Constants2 {
  
    // Add a cookie.
    public Cookie addCookie(Account account) {  
        Cookie cookie = new Cookie(ACCOUNT_COOKIE, account.getName() + ","  
                + account.getPassword());
        cookie.setMaxAge(DURATION_COOKIE_SAVE_MAX); //save cookie for 2 weeks.
        return cookie;  
    }
    
    public Cookie addCookie(int teamID, String password) {  
        Cookie cookie = new Cookie(TEAM_COOKIE, String.valueOf(teamID) + ","  
                + password);
        cookie.setMaxAge(DURATION_COOKIE_SAVE_MAX); //save cookie for 2 weeks.
        return cookie;  
    }  
  
  
    //get a cookie
    public boolean getCookie(HttpServletRequest request, Map<String, Object> session, AuthenticationService authenticationService) {  
        Cookie[] cookies = request.getCookies();  
        System.out.println("cookies: " + cookies);  
        if (cookies != null) {  
            for (Cookie cookie : cookies) {  
                System.out.println("cookie: " + cookie.getName());  
                if (ACCOUNT_COOKIE.equals(cookie.getName())) {  
                    String value = cookie.getValue();  
                    if (StringUtils.isNotBlank(value)) {  
                        String[] split = value.split(",");  
                        String username = split[0];  
                        String password = split[1];
                        
                        Account accountInput = new Account();
                        accountInput.setName(username.trim());
                        accountInput.setEncryptPassword(password.trim());

                        AuthenticationOutput output = authenticationService.verifyAccount(accountInput);

                        if (output.isValidFlg()) {  
                            session.put(ACCOUNT_SESSION, output.getAccount());
                            return true;  
                        }  
                    }  
                }  
            }  
        }  
        return false;  
    }  
  
    // delete cookie  
    public Cookie deleteCookie(HttpServletRequest request) {  
        Cookie[] cookies = request.getCookies();  
        if (cookies != null) {  
            for (Cookie cookie : cookies) {  
                if (ACCOUNT_COOKIE.equals(cookie.getName())) {  
                    cookie.setValue("");  
                    cookie.setMaxAge(0);  
                    return cookie;  
                }  
            }  
        }  
        return null;  
    }
}  